package com.xbongbong.paas.script.controller;

import com.xbongbong.paas.pojo.dto.FixDataJobDTO;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.pro.config.ProBaseConfig;
import com.xbongbong.pro.constant.XbbProConstant;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.saas.domain.entity.WorkOrderEntity;
import com.xbongbong.saas.domain.entity.WorkOrderFlowNodeEntity;
import com.xbongbong.saas.domain.entity.WorkOrderProductEntity;
import com.xbongbong.saas.domain.entity.WorkOrderStageEntity;
import com.xbongbong.saas.domain.entity.WorkOrderTemplateEntity;
import com.xbongbong.saas.enums.WorkOrderNodeStatusEnum;
import com.xbongbong.saas.enums.dictionary.AllOutBoundEnum;
import com.xbongbong.saas.model.WorkOrderFlowNodeModel;
import com.xbongbong.saas.model.WorkOrderModel;
import com.xbongbong.saas.model.WorkOrderStageModel;
import com.xbongbong.saas.model.WorkOrderTemplateModel;
import com.xbongbong.saas.service.WorkOrderProductService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;

/**
 *
 * @author 魏荣杰
 * @date 2021/4/22 12:15
 * @since
 * @version
 */
@RestController
@RequestMapping(XbbProConstant.API_ROOT_PREFIX + "/script/fixWorkOrder")
public class FixWorkOrderScriptController {
    private static final Logger LOG = LoggerFactory.getLogger(FixWorkOrderScriptController.class);

    @Resource
    private ProBaseConfig proBaseConfig;
    @Resource
    private WorkOrderModel workOrderModel;
    @Resource
    private WorkOrderTemplateModel workOrderTemplateModel;
    @Resource
    private WorkOrderStageModel workOrderStageModel;
    @Resource
    private WorkOrderFlowNodeModel workOrderFlowNodeModel;
    @Resource
    private WorkOrderProductService workOrderProductService;

    @PostMapping(value = "/fix")
    public String fix(@RequestBody @Valid FixDataJobDTO fixDataJobDTO, BindingResult br) throws Exception {
        if (!proBaseConfig.getXbbCode().equals(fixDataJobDTO.getXbbCode())) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100006);
        }
        List<String> corpidList = fixDataJobDTO.getCorpidList();
        if (corpidList == null || corpidList.isEmpty()) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, "公司id不能为空");
        }
        List<Long> dataIdList = fixDataJobDTO.getDataIdList();
        if (dataIdList == null || dataIdList.isEmpty()) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, "dataIdList不能为空");
        }
        String corpid = corpidList.get(0);
        Map<String, Object> param = new HashMap<>();
        param.put("corpid", corpid);
        param.put("del", 0);
        param.put("idIn", dataIdList);
        List<WorkOrderEntity> workOrderEntities = workOrderModel.findEntitys(param);

        Set<Long> templateIds = new HashSet<>();
        workOrderEntities.forEach(v -> templateIds.add(v.getTemplateId()));
        Map<Long, WorkOrderTemplateEntity> templateMap = workOrderTemplateModel.getTemplateMap(templateIds, corpid);

        Map<Long, List<WorkOrderStageEntity>> workOrderStageMap = new HashMap<>();
        templateIds.forEach(v -> {
            List<WorkOrderStageEntity> workOrderStageEntities = workOrderStageModel.workOrderStageListByTemplateId(corpid, v);
            workOrderStageMap.put(v, workOrderStageEntities);
        });

        for (WorkOrderEntity workOrderEntity : workOrderEntities) {
            Long templateId = workOrderEntity.getTemplateId();
            WorkOrderTemplateEntity workOrderTemplateEntity = templateMap.get(templateId);
            Integer isFree = workOrderTemplateEntity.getIsFree();
            if (Objects.equals(isFree, 0)) {
                List<WorkOrderStageEntity> workOrderStageEntities = workOrderStageMap.get(templateId);
                Integer expectedTime = 0;
                for (WorkOrderStageEntity v : workOrderStageEntities) {
                    expectedTime += v.getExpectedTime();
                }
                workOrderEntity.setExpectedTime(expectedTime);
            } else {
                workOrderEntity.setExpectedTime(workOrderTemplateEntity.getExpectedTime());
            }

            List<WorkOrderFlowNodeEntity> workOrderFlowNodeEntities = workOrderFlowNodeModel.getNode(workOrderEntity.getId(), null, corpid);
            long startTime = Long.MAX_VALUE;
            for (WorkOrderFlowNodeEntity workOrderFlowNodeEntity : workOrderFlowNodeEntities) {
                if (Objects.equals(workOrderFlowNodeEntity.getIsNow(), 1)) {
                    workOrderEntity.setNowStageId(workOrderFlowNodeEntity.getStageId());

                    if (Objects.equals(workOrderFlowNodeEntity.getStatus(), WorkOrderNodeStatusEnum.CLOSE.getCode())) {
                        workOrderEntity.setCloseTime(workOrderFlowNodeEntity.getEndTime());
                    }
                    if (Objects.equals(workOrderFlowNodeEntity.getStatus(), WorkOrderNodeStatusEnum.FINISH.getCode())) {
                        workOrderEntity.setEndTime(workOrderFlowNodeEntity.getEndTime());
                    }
                    if (Objects.equals(workOrderFlowNodeEntity.getStatus(), WorkOrderNodeStatusEnum.UNACCEPTED.getCode())) {
                        workOrderEntity.setType(workOrderFlowNodeEntity.getNodeType());
                    }

                }
                if (workOrderFlowNodeEntity.getStartTime() < startTime) {
                    startTime = workOrderFlowNodeEntity.getStartTime();
                }
            }
            workOrderEntity.setStartTime(startTime);
            if (!Objects.equals(workOrderEntity.getEndTime(), 0L)) {
                workOrderEntity.setActualTime((int) (workOrderEntity.getEndTime() - workOrderEntity.getStartTime()));
            }


            List<WorkOrderProductEntity> workOrderProductList = workOrderProductService.getSurplusProduct(workOrderEntity.getCorpid(), workOrderEntity.getId(), workOrderEntity, null);
            if (workOrderProductList.isEmpty()) {
                workOrderEntity.setAllOutbound(AllOutBoundEnum.ALL_OUT.getCode());
            } else {
                workOrderEntity.setAllOutbound(AllOutBoundEnum.NON_OUT.getCode());
            }

            workOrderModel.save(workOrderEntity);

        }


        return null;
    }
}
